package black.market.daum;

import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import black.market.location.MapContentProvider;
import black.market.main.BlackPublic;
import black.market.main.BlackPublic.Action;
import black.market.main.DownloadHtml;
import black.market.util.Log;

public class DaumApi {
	public static final String TAG = "DaumApi";
	private static final String DAUM_MAP_KEY = "aa9b77b842dc824460feb140d70e679522d2e2e5";
	private static final String DAUM_LOCAL_KEY = "b5a08287a94b7d10cd9bc35e299a19d787c3601d";

	private Context mContext;

	public DaumApi(Context context) {
		super();
		// TODO Auto-generated constructor stub
		this.mContext = context;
	}

	public DaumApi() {
		// TODO Auto-generated constructor stub
	}

	public String[] getTransGeoPoint(String pointX, String pointY, String transType, String callBack) {
		String resultPoint[] = new String[2];
		try {
			URL url = new URL("http://apis.daum.net/maps/transcoord?apikey=" + DAUM_LOCAL_KEY + "&x=" + pointX + "&y=" + pointY + "&fromCoord=WGS84&toCoord=" + transType + "&output=" + callBack);
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(url.openStream(), null);
			int parserEvent = parser.getEventType();
			while (parserEvent != XmlPullParser.END_DOCUMENT) {
				switch (parserEvent) {
				case XmlPullParser.START_TAG:
					String tag = parser.getName();
					if (tag.equals("result")) {
						resultPoint[0] = parser.getAttributeValue(null, "x");
						resultPoint[1] = parser.getAttributeValue(null, "y");
						double dx = Double.parseDouble(resultPoint[0]);
						double dy = Double.parseDouble(resultPoint[1]);
						resultPoint[0] = String.valueOf(Math.round(dy));
						resultPoint[1] = String.valueOf(Math.round(dx));
						BlackPublic.identifiesLog(TAG, "Type: " + transType + " resX: " + resultPoint[0] + ", resY: " + resultPoint[1]);
					}
					break;
				}
				parserEvent = parser.next();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultPoint;
	}

	/**
	 * @param lng
	 *            : x의 매개변수
	 * @param lat
	 *            : y의 매개변수(다음은 반대로 되어있다.)
	 * @param inputCoordSystem
	 *            : 입력하는 좌표의 체계 타입(WGS84, WTM등..)
	 * @param format
	 *            : simple 입력 시에 simple표기 된 정보만 출력
	 * @param output
	 *            : 출력 형식 xml(기본), json
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	public void geocodeToAddress(String lng, String lat, String inputCoordSystem, String format, String output) throws XmlPullParserException, IOException {
		DownloadHtml downloadHtml = new DownloadHtml();

		List<NameValuePair> httpGetParamList = new ArrayList<NameValuePair>();
		httpGetParamList.add(new BasicNameValuePair("apikey", DAUM_LOCAL_KEY));
		httpGetParamList.add(new BasicNameValuePair("longitude", lng));
		httpGetParamList.add(new BasicNameValuePair("latitude", lat));
		httpGetParamList.add(new BasicNameValuePair("inputCoordSystem", inputCoordSystem));
		httpGetParamList.add(new BasicNameValuePair("format", format));
		httpGetParamList.add(new BasicNameValuePair("output", output));
		String msg = downloadHtml.httpGetTypeReturn("http://apis.daum.net/local/geo/coord2addr?", httpGetParamList);
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser xmlPullParser = factory.newPullParser();
		xmlPullParser.setInput(new StringReader(msg));

		int eventType = xmlPullParser.getEventType();
		String sido = null;
		String gugun = null;
		String dong = null;
		boolean isRcode = false;

		Log.d(TAG, "geocodeToAddr return msg: " + msg);
		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				Log.d(TAG, "geocodeToAddr Start DOCUMENT");
				break;
			case XmlPullParser.END_DOCUMENT:

				break;
			case XmlPullParser.START_TAG:
				sido = xmlPullParser.getAttributeValue(null, "name1");
				gugun = xmlPullParser.getAttributeValue(null, "name2");
				dong = xmlPullParser.getAttributeValue(null, "name3");
				Log.d(TAG, "START_TAG return msg: " + sido + "/ " + gugun + "/ " + dong);
				break;
			case XmlPullParser.END_TAG:

				break;
			case XmlPullParser.TEXT:
				// if (isRcode) {
				// sido = xmlPullParser.getAttributeValue(null, "name1");
				// gugun = xmlPullParser.getAttributeValue(null, "name2");
				// dong = xmlPullParser.getAttributeValue(null, "name3");
				// ExamplePublic.debugLog(TAG, "TEXT return msg: " + sido + "/ "
				// + gugun + "/ " + dong);
				// }
				break;

			}
			eventType = xmlPullParser.next();
		}
		ContentValues cv = new ContentValues();
		if (sido != null && gugun != null && dong != null) {
			Log.d(TAG, "NOT NULL: " + sido + "/ " + gugun + "/ " + dong);
			cv.put(MapContentProvider.MAP_NAME1, sido);
			cv.put(MapContentProvider.MAP_NAME2, gugun);
			cv.put(MapContentProvider.MAP_NAME3, dong);
			mContext.getContentResolver().insert(MapContentProvider.MAP_ADDRESS_URI, cv);
			Intent intent = new Intent(Action.KMA_DATA_INTERVAL3H.toString());
			mContext.sendBroadcast(intent);
		}
	}

	public class DaumTransGeoList {
		public static final String TM = "TM";
		public static final String KTM = "KTM";
		public static final String UTM = "UTM";
		public static final String CONGNAMUL = "CONGNAMUL";
		public static final String BESSEL = "BESSEL";
		public static final String WTM = "WTM";
		public static final String WKTM = "WKTM";
		public static final String WUTM = "WUTM";
		public static final String WCONGNAMUL = "WCONGNAMUL";
		public static final String WGS84 = "WGS84";
	}

	public class DaumCallbackList {
		public static final String XML = "xml";
		public static final String JSON = "json";
		public static final String RSS = "rss";
	}

	public class DaumFormatList {
		public static final String FULL = "";
		public static final String SIMPLE = "simple";
	}
}
